package com.showsu.editor.utils.aliyun.moderaction;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.showsu.editor.enums.ModerationRiskLevelEnum;
import com.showsu.editor.utils.aliyun.BaseAliyunUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author: jph
 * @Description: 阿里云文本审核增强版工具类
 * @Date: Created in 16:54 下午 2024/06/25
 * @Modified By:
 */
@Slf4j
@Component
public class AliyunTextModerationUtil extends BaseAliyunUtil<Client> {

    @Value("${aliyun.vpc.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.vpc.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.vpc.endpoint}")
    private String endpoint;



    @Override
    public void initClient(String accessKeyId, String accessKeySecret, String endpoint) {
        try {
            this.client= this.createClient(accessKeyId,accessKeySecret,endpoint);
        }catch (Exception e) {
            System.out.println("阿里云文本审核增强版工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }
    @PostConstruct
    public void init(){
        System.out.println("开始实例化 阿里云文本审核增强版工具类");
        this.initClient(accessKeyId,accessKeySecret,endpoint);
        System.out.println("结束实例化 阿里云文本审核增强版工具类");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @param endpoint
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret,String endpoint) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Mts
        config.setEndpoint(endpoint);
        return new Client(config);
    }
    public TextModerationResponseBody.TextModerationResponseBodyData run( Client client,AliyunTextModerationServiceCodeEnum serviceCodeEnum,String content){
        // ====================== 3. 发起请求） ======================
        TextModerationResponseBody.TextModerationResponseBodyData result=null;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            System.out.println("text moderation content is empty");
            return result;
        }

         /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        TextModerationRequest textModerationRequest = new TextModerationRequest()
                .setService(serviceCodeEnum.getCode());

        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
//                    config.setRegionId("cn-beijing");
//                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
//                    client = new Client(config);
//                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }
            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody body = response.getBody();
                    Integer code = body.getCode();
                    if (code != null && code == 200) {
                        result = body.getData();
                    } else {
                        log.error("阿里云文本审核增强版工具类 参数:{} text moderation not success. code::{},conteng:{},",serviceCodeEnum.getMsg(),code,content);
                    }
                } else {
                    log.error("阿里云文本审核增强版工具类 参数:{} response not success. status:{},conteng:{},",serviceCodeEnum.getMsg(),response.getStatusCode(),content);
                }
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error("阿里云文本审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),content);
            // 诊断地址
            log.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            log.error("阿里云文本审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),content);
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return result;
    }

    public List<TextModerationResponseBody.TextModerationResponseBodyData> start(Client thisClient,AliyunTextModerationServiceCodeEnum serviceCodeEnum,String content) {
        List<TextModerationResponseBody.TextModerationResponseBodyData> result=new ArrayList<>();
        if(StringUtils.isNotBlank(content)){
            if(content.length()<=600){
                TextModerationResponseBody.TextModerationResponseBodyData data=run(thisClient,serviceCodeEnum,content);
                if(StringUtils.isNotBlank(data.getLabels())){
                    result.add(data);
                }
            }else{
                do{
                    String iContent=content.substring(0,600);
                    content=content.substring(590);
                    TextModerationResponseBody.TextModerationResponseBodyData data=run(thisClient,serviceCodeEnum,iContent);
                    if(StringUtils.isNotBlank(data.getLabels())){
                        result.add(data);
                    }
                }while (content.length()>600);
                TextModerationResponseBody.TextModerationResponseBodyData data=run(thisClient,serviceCodeEnum,content);
                if(StringUtils.isNotBlank(data.getLabels())){
                    result.add(data);
                }
            }

        }

        return result;
    }

    public List<TextModerationResponseBody.TextModerationResponseBodyData> start(String accessKeyId,String accessKeySecret,String endpoint,AliyunTextModerationServiceCodeEnum serviceCodeEnum,String content) {
        try {
            Client newClient= this.createClient(accessKeyId,accessKeySecret,endpoint);
            return start(newClient,serviceCodeEnum,content);
        }catch (Exception e) {
            log.error("start方法 阿里云文本审核增强版工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public List<TextModerationResponseBody.TextModerationResponseBodyData> start(String content) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint,AliyunTextModerationServiceCodeEnum.comment_detection,content);
        }
        return start(this.client,AliyunTextModerationServiceCodeEnum.comment_detection,content);
    }
    public List<TextModerationResponseBody.TextModerationResponseBodyData> start(AliyunTextModerationServiceCodeEnum serviceCodeEnum,String content) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,content);
        }
        return start(this.client,serviceCodeEnum,content);
    }
    public Boolean startGetBoolean(AliyunTextModerationServiceCodeEnum serviceCodeEnum,String content) {
        List<TextModerationResponseBody.TextModerationResponseBodyData> list=null;
        if(this.client==null){
            list=start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,content);
        }else{
            list=start(this.client,serviceCodeEnum,content);
        }
        int count=0;
        if(list.size()>0){
            for(TextModerationResponseBody.TextModerationResponseBodyData data : list){
                if(StringUtils.equals(data.getLabels(),"ad")){
                    continue;
                }
                if(StringUtils.equals(data.getLabels(),"nonsense")){
                    continue;
                }
                if(StringUtils.equals(data.getLabels(),"ad_compliance")){
                    continue;
                }
                count++;
            }
        }
        if(count>0){
            return true;
        }else{
            return false;
        }
    }

    public List<TextModerationResponseBody.TextModerationResponseBodyData> start(String serviceCode,String content) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint,AliyunTextModerationServiceCodeEnum.getByCode(serviceCode),content);
        }
        return start(this.client,AliyunTextModerationServiceCodeEnum.getByCode(serviceCode),content);
    }



    public TextModerationPlusResponseBody.TextModerationPlusResponseBodyData PlusRun( Client client,AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum,String content){
        // ====================== 3. 发起请求） ======================
        TextModerationPlusResponseBody.TextModerationPlusResponseBodyData result=null;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            System.out.println("text moderation content is empty");
            return result;
        }

         /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        TextModerationPlusRequest textModerationRequest = new TextModerationPlusRequest()
                .setService(serviceCodeEnum.getCode());

        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 调用方法获取检测结果。
            TextModerationPlusResponse response = client.textModerationPlusWithOptions(textModerationRequest, runtime);
            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
//                    config.setRegionId("cn-beijing");
//                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
//                    client = new Client(config);
//                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }
            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationPlusResponseBody body = response.getBody();
                    Integer code = body.getCode();
                    if (code != null && code == 200) {
                        result = body.getData();
                    } else {
                        log.error("阿里云文本审核增强版工具类 参数:{} text moderation not success. code::{},conteng:{},",serviceCodeEnum.getMsg(),code,content);
                    }
                } else {
                    log.error("阿里云文本审核增强版工具类 参数:{} response not success. status:{},conteng:{},",serviceCodeEnum.getMsg(),response.getStatusCode(),content);
                }
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error("阿里云文本审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),content);
            // 诊断地址
            log.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            log.error("阿里云文本审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),content);
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return result;
    }

    public List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> PlusStart(Client thisClient,AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum,String content) {
        List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> result=new ArrayList<>();
        if(StringUtils.isNotBlank(content)){
            while (content.length()>600){
                String iContent=content.substring(0,600);
                content=content.substring(590);
                TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data=PlusRun(thisClient,serviceCodeEnum,iContent);
                List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyDataResult> resultList=data.getResult();
                if(resultList.size()>1){
                    result.add(data);
                }else if(resultList.size()>0){
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyDataResult bodyDataResult=resultList.get(0);
                    if(bodyDataResult!=null){
                        if(!StringUtils.contains(bodyDataResult.getLabel(),"nonLabel")){
                            result.add(data);
                        }
                    }
                }
            }
            TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data=PlusRun(thisClient,serviceCodeEnum,content);
            if (data == null) {
                return result;
            }
            List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyDataResult> resultList=data.getResult();
            if (CollectionUtils.isEmpty(resultList)) {
                return result;
            }
            if(resultList.size()>1){
                result.add(data);
            }else if(resultList.size()>0){
                TextModerationPlusResponseBody.TextModerationPlusResponseBodyDataResult bodyDataResult=resultList.get(0);
                if(bodyDataResult!=null){
                    if(!StringUtils.contains(bodyDataResult.getLabel(),"nonLabel")){
                        result.add(data);
                    }
                }
            }

        }
        return result;
    }

    public List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> PlusStart(String accessKeyId,String accessKeySecret,String endpoint,AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum,String content) {
        try {
            Client newClient= this.createClient(accessKeyId,accessKeySecret,endpoint);
            return PlusStart(newClient,serviceCodeEnum,content);
        }catch (Exception e) {
            log.error("start方法 阿里云文本审核增强版工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> PlusStart(String content) {
        if(this.client==null){
            return PlusStart(accessKeyId,accessKeySecret,endpoint,AliyunTextModerationPlusServiceCodeEnum.comment_detection_pro,content);
        }
        return PlusStart(this.client,AliyunTextModerationPlusServiceCodeEnum.comment_detection_pro,content);
    }
    public List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> PlusStart(AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum,String content) {
        if(this.client==null){
            return PlusStart(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,content);
        }
        return PlusStart(this.client,serviceCodeEnum,content);
    }

    public List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> PlusStart(String serviceCode,String content) {
        if(this.client==null){
            return PlusStart(accessKeyId,accessKeySecret,endpoint,AliyunTextModerationPlusServiceCodeEnum.getByCode(serviceCode),content);
        }
        return PlusStart(this.client,AliyunTextModerationPlusServiceCodeEnum.getByCode(serviceCode),content);
    }

    public Boolean PlusStartGetBoolean(AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum,String content) {
        List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> list=null;
        if(this.client==null){
            list=PlusStart(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,content);
        }else{
            list=PlusStart(this.client,serviceCodeEnum,content);
        }
        int count= list.size();
        if(count>0){
            return true;
        }else{
            return false;
        }
    }

    public AliyunModerationRiskLevelEnum PlusStartGetRiskLevel(AliyunTextModerationPlusServiceCodeEnum serviceCodeEnum, String content) {
        List<TextModerationPlusResponseBody.TextModerationPlusResponseBodyData> list=null;
        if(this.client==null){
            list=PlusStart(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,content);
        }else{
            list=PlusStart(this.client,serviceCodeEnum,content);
        }
        AliyunModerationRiskLevelEnum riskLevelEnum=AliyunModerationRiskLevelEnum.none;
        for(TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data : list){
            AliyunModerationRiskLevelEnum thisLevel= AliyunModerationRiskLevelEnum.getByCode(data.getRiskLevel());
            if(AliyunModerationRiskLevelEnum.high.equals(thisLevel)){
                riskLevelEnum=AliyunModerationRiskLevelEnum.high;
                break;
            }
            if(thisLevel.getLevel()> riskLevelEnum.getLevel()){
                riskLevelEnum=thisLevel;
            }
        }
        return riskLevelEnum;
    }



}
